import tkinter as tk
import mysql.connector

def tkwindows1():
    top = tk.Tk()
    top.title("生成Word文档")
    top.geometry("600x300")

    # 单位
    unit_label = tk.Label(top, text="单位:")
    unit_label.pack()
    unit_entry = tk.Entry(top)
    unit_entry.pack()

    # 姓名
    name_label = tk.Label(top, text="姓名:")
    name_label.pack()
    name_entry = tk.Entry(top)
    name_entry.pack()

    # 职务
    job_label = tk.Label(top, text="职务:")
    job_label.pack()
    job_entry = tk.Entry(top)
    job_entry.pack()

    # 联系方式
    contact_label = tk.Label(top, text="联系方式:")
    contact_label.pack()
    contact_entry = tk.Entry(top)
    contact_entry.pack()

    # 联系地址
    address_label = tk.Label(top, text="联系地址:")
    address_label.pack()
    address_entry = tk.Entry(top)
    address_entry.pack()

    def insert_into_database():
        unit = unit_entry.get()
        name = name_entry.get()
        job = job_entry.get()
        phone = contact_entry.get()
        address = address_entry.get()

        try:
            # 连接数据库
            mydb = mysql.connector.connect(
                host="localhost",
                user="root",
                password="1234Qwer",
                database="StudyClass"
            )
            mycursor = mydb.cursor()

            # 插入数据的SQL语句
            sql = ("INSERT INTO teacher (Name, Unit, Job, Phone, Address) "
                   "VALUES (%s, %s, %s, %s, %s)")
            val = (name, unit, job, phone, address)
            mycursor.execute(sql, val)

            # 提交事务
            mydb.commit()
            print("数据插入成功")
        except mysql.connector.Error as err:
            print(f"数据插入失败: {err}")
        finally:
            # 关闭数据库连接
            mydb.close()

    # 打印信息按钮（这里改为插入数据库按钮）
    print_button = tk.Button(top, text="插入数据库",
                             command=insert_into_database)
    print_button.pack()

if __name__ == "__main__":
    tkwindows1()
    tk.mainloop()